package cn.sangyy.basic.interceptor;

import cn.sangyy.basic.common.code.CodeEnum;
import cn.sangyy.basic.exception.CarAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author SangYY
 * @date: 2023/06/02/23:24
 */
@Component
public class CarInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        CarAssert.assertStrNotBlank(token, CodeEnum.LOGIN_AUTH);
        Object user = redisTemplate.opsForValue().get(token);
        CarAssert.assertNotNull(user,CodeEnum.LOGIN_USERNAME_IS_EXPIRE);
        return true;
    }


    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
}
